<?php

namespace app\controller;

use support\Request;
use support\Response;
use Carbon\Carbon;
use app\model\Room;
use app\model\AccountingRecord;

class AccountingController
{
    /**
     * 获取房间记录
     */
    public function getRoomRecords(Request $request): Response
    {
        $roomId = $request->get('room_id');
        // 安全获取分页参数，确保是有效的整数
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 20);
        $type = $request->get('type', 'score'); // 支持按类型筛选

        // 验证分页参数的有效性
        if ($page < 1) {
            $page = 1;
        }
        if ($pageSize < 1 || $pageSize > 100) {
            $pageSize = 20; // 默认值，最大100
        }

        // 添加调试日志
        error_log("getRoomRecords called with room_id: $roomId, page: $page, page_size: $pageSize, type: $type");

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }


        try {
            // 验证房间是否存在
            $room = Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }

            // 获取房间的记账记录，支持分页和类型筛选
            $query = AccountingRecord::where('room_id', $roomId);
            
            // 根据类型筛选记录
            if ($type === 'tea_meal') {
                $query->where('type', 'tea_meal');
            } else {
                $query->where('type', 'score'); // 默认只获取记账类型的记录
            }
            
            $records = $query->with(['user', 'targetUser'])
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            // 添加调试日志
            error_log("Found " . $records->count() . " records for room $roomId");

            // 格式化记录数据
            $formattedRecords = $records->map(function ($record) {
                // 根据记录类型生成显示文案
                $actionText = $this->getRecordActionText($record->type);
                $showScore = $record->type === 'score';
                $showTarget = $record->type === 'score';
                
                return [
                    'id' => $record->id,
                    'room_id' => $record->room_id,
                    'user_id' => $record->user_id,
                    'target_user_id' => $record->target_user_id,
                    'score' => $record->score,
                    'description' => $record->description,
                    'type' => $record->type,
                    'is_settled' => $record->is_settled,
                    'created_at' => $record->created_at->format('Y-m-d H:i:s'),
                    'user' => $record->user ? [
                        'id' => $record->user->id,
                        'nickname' => $record->user->nickname,
                        'avatar' => $record->user->avatar
                    ] : null,
                    'target_user' => $record->targetUser ? [
                        'id' => $record->targetUser->id,
                        'nickname' => $record->targetUser->nickname,
                        'avatar' => $record->targetUser->avatar
                    ] : null,
                    // 新增字段用于前端显示
                    'action_text' => $actionText,
                    'show_score' => $showScore,
                    'show_target' => $showTarget
                ];
            });

            return json([
                'success' => true,
                'data' => [
                    'records' => $formattedRecords,
                    'has_more' => $records->hasMorePages(),
                    'current_page' => $records->currentPage(),
                    'last_page' => $records->lastPage(),
                    'total' => $records->total()
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取房间记录失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取房间记录失败']);
        }
    }

    /**
     * 添加记录
     */
    public function addRecord(Request $request): Response
    {
        $data = $request->post();
        $roomId = $data['room_id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        $targetUserId = $data['target_user_id'] ?? 0;
        $score = $data['score'] ?? 0;
        $description = $data['description'] ?? '';
        $type = $data['type'] ?? 'score';

        // 记录请求数据用于调试
        error_log('AccountingController::addRecord - 接收到的数据: ' . json_encode($data));

        if (!$roomId || !$userId || !$targetUserId) {
            return json(['success' => false, 'message' => '参数不完整', 'debug' => [
                'room_id' => $roomId,
                'user_id' => $userId,
                'target_user_id' => $targetUserId
            ]]);
        }

        // 验证数据类型
        if (!is_numeric($roomId) || !is_numeric($userId) || !is_numeric($targetUserId)) {
            return json(['success' => false, 'message' => '参数类型错误，ID必须为数字']);
        }

        if (!is_numeric($score)) {
            return json(['success' => false, 'message' => '分数必须为数字']);
        }

        // 验证分数不能为负数或零
        if ($score <= 0) {
            return json(['success' => false, 'message' => '支出金额必须大于0']);
        }

        try {
            // 验证房间是否存在
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }

            // 验证用户是否存在
            $user = \app\model\User::find($userId);
            if (!$user) {
                return json(['success' => false, 'message' => '用户不存在']);
            }

            // 验证目标用户是否存在
            $targetUser = \app\model\User::find($targetUserId);
            if (!$targetUser) {
                return json(['success' => false, 'message' => '目标用户不存在']);
            }

            // 创建记账记录 - 支出方记录负数，收入方记录正数
            $recordData = [
                'room_id' => (int)$roomId,
                'user_id' => (int)$userId,
                'target_user_id' => (int)$targetUserId,
                'score' => -(int)$score, // 支出方记录负数
                'description' => $description,
                'type' => $type,
                'is_settled' => 0
            ];

            error_log('AccountingController::addRecord - 准备创建记录: ' . json_encode($recordData));

            // 使用数据库事务确保数据一致性
            $record = \Illuminate\Database\Capsule\Manager::transaction(function () use ($recordData, $roomId, $userId, $targetUserId, $score, $type) {
                try {
                    // 创建记账记录
                    $record = \app\model\AccountingRecord::createRecord($recordData);
                    error_log('AccountingController::addRecord - 记录创建成功，ID: ' . $record->id);
                    
                    // 更新收入方分数（正数）
                    $this->updateRoomUserScore($roomId, $targetUserId, $score);
                    error_log('AccountingController::addRecord - 收入方分数更新成功');
                    
                    // 更新支出方分数（负数）
                    $this->updateRoomUserScore($roomId, $userId, -$score);
                    error_log('AccountingController::addRecord - 支出方分数更新成功');
                    
                    // 如果是记分记录（非茶饭费），检查是否需要自动扣除茶饭费
                    $teaMealDeduction = null;
                    if ($type === 'score' && $score > 0) {
                        try {
                            $teaMealDeduction = \app\service\TeaMealService::autoDeductTeaMeal($roomId, $targetUserId, $score);
                            
                            if ($teaMealDeduction && $teaMealDeduction['deducted']) {
                                error_log("自动扣除茶饭费: 用户{$targetUserId} 赢{$score}分，扣除{$teaMealDeduction['amount']}分茶饭费");
                            }
                        } catch (\Exception $teaMealException) {
                            error_log('自动扣除茶饭费失败，但不影响主要功能: ' . $teaMealException->getMessage());
                            $teaMealDeduction = ['deducted' => false, 'amount' => 0];
                        }
                    }
                    
                    // 记录审计日志
                    try {
                        $this->logTransaction($record, $roomId, $userId, $targetUserId, $score);
                    } catch (\Exception $logException) {
                        error_log('记录审计日志失败，但不影响主要功能: ' . $logException->getMessage());
                    }
                    
                    error_log('AccountingController::addRecord - 事务执行成功');
                    return ['record' => $record, 'tea_meal_deduction' => $teaMealDeduction];
                } catch (\Exception $e) {
                    error_log('AccountingController::addRecord - 事务内异常: ' . $e->getMessage());
                    error_log('AccountingController::addRecord - 堆栈跟踪: ' . $e->getTraceAsString());
                    throw $e; // 重新抛出异常，让事务回滚
                }
            });

            // 提取记录和茶饭费扣除信息
            if (!isset($record['record'])) {
                error_log('AccountingController::addRecord - 错误: 事务返回数据格式异常');
                return json(['success' => false, 'message' => '处理失败：数据格式异常']);
            }
            
            $actualRecord = $record['record'];
            $teaMealDeduction = $record['tea_meal_deduction'] ?? null;

            // 发送WebSocket消息通知房间内其他用户
            try {
                $websocketService = \app\service\WebSocketService::getInstance();
                
                // 发送支出记录消息
                $websocketService->sendExpenseRecordedMessage(
                    $roomId,
                    $userId,
                    $targetUserId,
                    $score,
                    $type
                );
                
                // 发送收入方分数更新消息
                $websocketService->sendScoreUpdateMessage($roomId, $targetUserId, $score);
                
                // 发送支出方分数更新消息
                $websocketService->sendScoreUpdateMessage($roomId, $userId, -$score);
                
                // 如果有茶饭费扣除，发送茶饭费扣除消息
                if ($teaMealDeduction && $teaMealDeduction['deducted']) {
                    $websocketService->sendTeaMealDeductionMessage(
                        $roomId,
                        $targetUserId,
                        $teaMealDeduction['amount'],
                        $score
                    );
                }
                
            } catch (\Exception $wsException) {
                error_log('发送WebSocket消息失败: ' . $wsException->getMessage());
                // WebSocket消息发送失败不影响主要功能
            }

            // 清除排行榜缓存，因为用户积分可能发生变化
            try {
                $leaderboardController = new \app\controller\LeaderboardController();
                $leaderboardController->clearLeaderboardCache();
            } catch (\Exception $cacheException) {
                error_log('清除排行榜缓存失败: ' . $cacheException->getMessage());
                // 缓存清除失败不影响主要功能
            }

            $responseData = [
                'record' => [
                    'id' => $actualRecord->id,
                    'score' => $actualRecord->score,
                    'description' => $actualRecord->description,
                    'type' => $actualRecord->type,
                    'created_at' => $actualRecord->created_at->format('Y-m-d H:i:s')
                ]
            ];

            // 如果有茶饭费扣除，添加到响应中
            if ($teaMealDeduction && isset($teaMealDeduction['deducted']) && $teaMealDeduction['deducted']) {
                $responseData['tea_meal_deduction'] = $teaMealDeduction;
            }

            $response = [
                'success' => true,
                'data' => $responseData
            ];
            
            error_log('AccountingController::addRecord - 准备返回成功响应: ' . json_encode($response, JSON_UNESCAPED_UNICODE));
            
            return json($response);
        } catch (\Exception $e) {
            error_log('AccountingController::addRecord - 捕获异常: ' . $e->getMessage());
            error_log('AccountingController::addRecord - 异常文件: ' . $e->getFile());
            error_log('AccountingController::addRecord - 异常行号: ' . $e->getLine());
            error_log('AccountingController::addRecord - 堆栈跟踪: ' . $e->getTraceAsString());
            
            $errorResponse = [
                'success' => false,
                'message' => '添加记录失败：' . $e->getMessage()
            ];
            
            error_log('AccountingController::addRecord - 返回错误响应: ' . json_encode($errorResponse, JSON_UNESCAPED_UNICODE));
            
            return json($errorResponse);
        }
    }

    /**
     * 获取用户个人结算单
     */
    public function getUserSettlement(Request $request): Response
    {
        $userId = $request->get('user_id');
        $roomId = $request->get('room_id');

        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            // 获取用户在房间中的所有记录
            $records = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)
                          ->orWhere('target_user_id', $userId);
                })
                ->with(['user', 'targetUser'])
                ->orderBy('created_at', 'desc')
                ->get();

            if ($records->isEmpty()) {
                return json(['success' => false, 'message' => '未产生数据，不需要结算']);
            }

            // 计算个人总分
            $totalScore = 0;
            $unsettledItems = [];
            $settledItems = [];

            foreach ($records as $record) {
                if ($record->user_id == $userId) {
                    // 用户主动记分给他人
                    $totalScore += $record->score;
                    $unsettledItems[] = [
                        'id' => $record->id,
                        'type' => 'give',
                        'target_user' => $record->targetUser->nickname ?? '未知用户',
                        'amount' => abs($record->score),
                        'description' => $record->description,
                        'created_at' => $record->created_at->format('m-d H:i')
                    ];
                } elseif ($record->target_user_id == $userId) {
                    // 他人记分给用户
                    $totalScore -= $record->score; // 注意这里是减法，因为别人给用户加分
                    $settledItems[] = [
                        'id' => $record->id,
                        'type' => 'receive',
                        'from_user' => $record->user->nickname ?? '未知用户',
                        'amount' => abs($record->score),
                        'description' => $record->description,
                        'created_at' => $record->created_at->format('m-d H:i')
                    ];
                }
            }

            // 生成结算状态
            $settlementStatus = 'unsettled';
            $settlementMessage = '';
            
            if ($totalScore > 0) {
                $settlementStatus = 'win';
                $settlementMessage = '获得大神称号,今晚你买单!';
            } elseif ($totalScore < 0) {
                $settlementStatus = 'loss';
                $settlementMessage = '获得大侠称号,兄弟们发家致富全靠你了!';
            } else {
                $settlementStatus = 'draw';
                $settlementMessage = '平局收场，下次再战!';
            }

            return json([
                'success' => true,
                'data' => [
                    'total_score' => $totalScore,
                    'settlement_status' => $settlementStatus,
                    'settlement_message' => $settlementMessage,
                    'unsettled_items' => $unsettledItems,
                    'settled_items' => $settledItems,
                    'room_info' => [
                        'id' => $roomId,
                        'name' => '打牌记账房间'
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'message' => '获取结算单失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取房间总结算
     */
    public function getRoomSettlement(Request $request): Response
    {
        $roomId = $request->get('room_id');

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            // 获取房间内所有用户（包括已离开的）
            $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->with('user')
                ->get();
            
            if ($roomUsers->isEmpty()) {
                // 房间内没有用户，返回空的结算数据
                return json([
                    'success' => true,
                    'data' => [
                        'room_id' => $roomId,
                        'settlement_data' => [],
                        'total_transactions' => 0,
                        'generated_at' => date('Y-m-d H:i:s'),
                        'no_users' => true // 标识没有用户
                    ]
                ]);
            }

            $settlementData = [];
            // 先获取所有score类型的记录，用于统计总交易次数
            $allRecords = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where('type', 'score')
                ->get();
            $totalTransactions = $allRecords->count();

            // 为每个用户计算结算
            foreach ($roomUsers as $roomUser) {
                $userId = $roomUser->user_id;
                $userName = $roomUser->user->nickname ?? '未知用户';
                
                // 获取该用户的所有记录
                $records = \app\model\AccountingRecord::where('room_id', $roomId)
                    ->where(function($query) use ($userId) {
                        $query->where('user_id', $userId)
                              ->orWhere('target_user_id', $userId);
                    })
                    ->where('type', 'score')
                    ->with(['user', 'targetUser'])
                    ->get();

                $userTotal = 0;
                $payments = [];

                foreach ($records as $record) {
                    if ($record->user_id == $userId) {
                        // 用户主动记分给他人
                        $userTotal += $record->score;
                        $payments[] = [
                            'to' => $record->targetUser->nickname ?? '未知用户',
                            'amount' => abs($record->score),
                            'type' => 'give'
                        ];
                    } elseif ($record->target_user_id == $userId) {
                        // 他人记分给用户
                        $userTotal -= $record->score;
                        $payments[] = [
                            'from' => $record->user->nickname ?? '未知用户',
                            'amount' => abs($record->score),
                            'type' => 'receive'
                        ];
                    }
                }

                if ($userTotal != 0 || !empty($payments)) {
                    $settlementData[] = [
                        'user_id' => $userId,
                        'user_name' => $userName,
                        'total_score' => $userTotal,
                        'payments' => $payments
                    ];
                }
            }

            if (empty($settlementData)) {
                return json(['success' => false, 'message' => '未产生数据，不需要结算']);
            }

            // 检查是否有有意义的交易数据
            $hasSignificantTransactions = false;
            foreach ($settlementData as $userSettlement) {
                if ($userSettlement['total_score'] != 0 || count($userSettlement['payments']) > 1) {
                    $hasSignificantTransactions = true;
                    break;
                }
            }

            if (!$hasSignificantTransactions) {
                return json(['success' => false, 'message' => '交易数据不足，暂不需要结算']);
            }

            // 获取房间信息
            $room = \app\model\Room::find($roomId);
            
            return json([
                'success' => true,
                'data' => [
                    'room_id' => $roomId,
                    'room_code' => $room ? $room->room_code : $roomId,
                    'settlement_data' => $settlementData,
                    'total_transactions' => $totalTransactions,
                    'generated_at' => date('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'message' => '获取房间结算失败：' . $e->getMessage()]);
        }
    }

    /**
     * 发送结算结果到房间
     */
    public function sendSettlementToRoom(Request $request): Response
    {
        $data = $request->post();
        $roomId = $data['room_id'] ?? 0;
        $userId = $data['user_id'] ?? 0;

        if (!$roomId || !$userId) {
            return json(['success' => false, 'message' => '参数不完整']);
        }

        try {
            // 获取房间结算数据
            $settlementResult = $this->getRoomSettlementData($roomId);

            if (!$settlementResult['success']) {
                return json(['success' => false, 'message' => $settlementResult['message']]);
            }

            $settlementData = $settlementResult['data']['settlement_data'];
            
            // 生成结算消息
            $settlementMessage = "🏆 房间结算完成！\n\n";
            
            foreach ($settlementData as $userSettlement) {
                $userName = $userSettlement['user_name'];
                $totalScore = $userSettlement['total_score'];
                
                if ($totalScore > 0) {
                    $settlementMessage .= "💰 {$userName} 获得 +{$totalScore} 分\n";
                } elseif ($totalScore < 0) {
                    $settlementMessage .= "💸 {$userName} 需要支付 " . abs($totalScore) . " 分\n";
                }
                
                // 添加具体支付明细
                foreach ($userSettlement['payments'] as $payment) {
                    if ($payment['type'] === 'give') {
                        $settlementMessage .= "   → 向 {$payment['to']} 支付 {$payment['amount']} 分\n";
                    } elseif ($payment['type'] === 'receive') {
                        $settlementMessage .= "   ← 从 {$payment['from']} 获得 {$payment['amount']} 分\n";
                    }
                }
                $settlementMessage .= "\n";
            }

            // 使用数据库事务确保结算的原子性
            $settlementResult = \Illuminate\Database\Capsule\Manager::transaction(function () use ($settlementData, $roomId) {
                // 更新用户总分数
                $this->updateUsersTotalScore($settlementData);
                
                // 标记房间为已结算
                $this->markRoomAsSettled($roomId);
                
                // 标记所有相关记录为已结算
                $this->markRecordsAsSettled($roomId);
                
                return [
                    'success' => true,
                    'updated_users' => count($settlementData),
                    'room_id' => $roomId
                ];
            });
            
            error_log('房间结算事务完成: ' . json_encode($settlementResult));
            
            // 这里可以添加WebSocket推送逻辑，将消息发送到房间
            // 暂时返回成功，实际项目中需要集成WebSocket
            
            return json([
                'success' => true,
                'data' => [
                    'message' => $settlementMessage,
                    'settlement_data' => $settlementData,
                    'sent_at' => date('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'message' => '发送结算结果失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取用户房间流水记录
     */
    public function getUserRoomRecords(Request $request): Response
    {
        $userId = $request->get('user_id');
        $roomId = $request->get('room_id');
        // 安全获取分页参数，确保是有效的整数
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 20);

        // 验证分页参数的有效性
        if ($page < 1) {
            $page = 1;
        }
        if ($pageSize < 1 || $pageSize > 100) {
            $pageSize = 20; // 默认值，最大100
        }

        if (!$userId || !$roomId) {
            return json(['success' => false, 'message' => '用户ID和房间ID不能为空']);
        }

        try {
            // 验证用户是否存在
            $user = \app\model\User::find($userId);
            if (!$user) {
                return json(['success' => false, 'message' => '用户不存在']);
            }

            // 验证房间是否存在
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }

            // 获取用户在该房间的所有记录
            $records = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)
                          ->orWhere('target_user_id', $userId);
                })
                ->with(['user', 'targetUser'])
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            // 格式化记录数据
            $formattedRecords = $records->map(function ($record) {
                // 根据记录类型生成显示文案
                $actionText = $this->getRecordActionText($record->type);
                $showScore = $record->type === 'score';
                $showTarget = $record->type === 'score';
                
                // 判断是支出还是收入
                $isExpense = $record->user_id == $record->target_user_id; // 自己给自己（系统记录）
                $isIncome = $record->target_user_id != $record->user_id && $record->type == 'score';
                $isOutgoing = $record->user_id != $record->target_user_id && $record->type == 'score';
                
                return [
                    'id' => $record->id,
                    'room_id' => $record->room_id,
                    'user_id' => $record->user_id,
                    'target_user_id' => $record->target_user_id,
                    'score' => $record->score,
                    'description' => $record->description,
                    'type' => $record->type,
                    'is_settled' => $record->is_settled,
                    'created_at' => $record->created_at->format('Y-m-d H:i:s'),
                    'user' => $record->user ? [
                        'id' => $record->user->id,
                        'nickname' => $record->user->nickname,
                        'avatar' => $record->user->avatar
                    ] : null,
                    'target_user' => $record->targetUser ? [
                        'id' => $record->targetUser->id,
                        'nickname' => $record->targetUser->nickname,
                        'avatar' => $record->targetUser->avatar
                    ] : null,
                    // 新增字段用于前端显示
                    'action_text' => $actionText,
                    'show_score' => $showScore,
                    'show_target' => $showTarget,
                    'is_expense' => $isOutgoing,
                    'is_income' => $isIncome
                ];
            });

            return json([
                'success' => true,
                'data' => [
                    'records' => $formattedRecords,
                    'has_more' => $records->hasMorePages(),
                    'current_page' => $records->currentPage(),
                    'last_page' => $records->lastPage(),
                    'total' => $records->total()
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户房间流水记录失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取记录失败：' . $e->getMessage()]);
        }
    }

    /**
     * 根据记录类型获取显示文案
     */
    private function getRecordActionText($type)
    {
        switch ($type) {
            case 'score':
                return '记分给';
            case 'user_joined':
                return '进入了房间';
            case 'user_left':
                return '离开了房间';
            case 'user_rejoined':
                return '回到了房间';
            case 'manual_settlement':
                return '房主手动结算';
            default:
                return $type;
        }
    }

    /**
     * 更新房间用户分数
     */
    private function updateRoomUserScore($roomId, $userId, $score)
    {
        try {
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();
            
            if (!$roomUser) {
                throw new \Exception("房间用户关系不存在: room_id={$roomId}, user_id={$userId}");
            }
            
            // 更新分数
            $roomUser->updateScore($score);
            
            error_log("房间用户分数已更新: room_id={$roomId}, user_id={$userId}, score_change={$score}, new_score={$roomUser->current_score}");
            
            return $roomUser;
        } catch (\Exception $e) {
            error_log('更新房间用户分数失败: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 获取房间结算数据（私有方法，返回数组而不是Response对象）
     */
    private function getRoomSettlementData($roomId)
    {
        try {
            // 获取房间内所有用户
            $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->with('user')
                ->get();

            // 如果房间内没有活跃用户，获取所有历史用户进行结算
            if ($roomUsers->isEmpty()) {
                // 检查房间是否存在
                $room = \app\model\Room::find($roomId);
                if (!$room) {
                    return ['success' => false, 'message' => '房间不存在'];
                }
                
                // 获取所有参与过房间的用户（包括已离开的）
                $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                    ->with('user')
                    ->get();
                
                if ($roomUsers->isEmpty()) {
                    // 如果连历史用户都没有，返回空结算数据
                    return [
                        'success' => true,
                        'data' => [
                            'room_id' => $roomId,
                            'settlement_data' => [],
                            'total_transactions' => 0,
                            'generated_at' => date('Y-m-d H:i:s')
                        ]
                    ];
                }
            }

            $settlementData = [];
            // 先获取所有score类型的记录，用于统计总交易次数
            $allRecords = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where('type', 'score')
                ->get();
            $totalTransactions = $allRecords->count();

            // 为每个用户计算结算
            foreach ($roomUsers as $roomUser) {
                $userId = $roomUser->user_id;
                $userName = $roomUser->user->nickname ?? '未知用户';
                
                // 获取该用户的所有记录，只获取score类型的记录
                $records = \app\model\AccountingRecord::where('room_id', $roomId)
                    ->where(function($query) use ($userId) {
                        $query->where('user_id', $userId)
                              ->orWhere('target_user_id', $userId);
                    })
                    ->where('type', 'score') // 只获取score类型的记录
                    ->with(['user', 'targetUser'])
                    ->get();

                $userTotal = 0;
                $payments = [];

                foreach ($records as $record) {
                    // 添加调试日志
                    error_log("处理记录: ID={$record->id}, user_id={$record->user_id}, target_user_id={$record->target_user_id}, score={$record->score}, type={$record->type}");
                    
                    if ($record->user_id == $userId) {
                        // 用户主动记分给他人（支出，负数）
                        $userTotal += $record->score; // record->score已经是负数
                        // 只显示非零的支付记录
                        if (abs($record->score) > 0) {
                            $payments[] = [
                                'to' => $record->targetUser->nickname ?? '未知用户',
                                'amount' => abs($record->score), // 显示正数
                                'type' => 'give'
                            ];
                        } else {
                            error_log("跳过0分支付记录: user_id={$record->user_id}, score={$record->score}");
                        }
                    } elseif ($record->target_user_id == $userId) {
                        // 他人记分给用户（收入，正数）
                        $userTotal -= $record->score; // record->score是负数，所以减去负数等于加上正数
                        // 只显示非零的接收记录
                        if (abs($record->score) > 0) {
                            $payments[] = [
                                'from' => $record->user->nickname ?? '未知用户',
                                'amount' => abs($record->score), // 显示正数
                                'type' => 'receive'
                            ];
                        } else {
                            error_log("跳过0分接收记录: target_user_id={$record->target_user_id}, score={$record->score}");
                        }
                    }
                }

                if ($userTotal != 0 || !empty($payments)) {
                    $settlementData[] = [
                        'user_id' => $userId,
                        'user_name' => $userName,
                        'total_score' => $userTotal,
                        'payments' => $payments
                    ];
                }
            }

            if (empty($settlementData)) {
                // 即使没有交易数据，也允许房主结算房间（比如房间内只有房主一个人）
                return [
                    'success' => true,
                    'data' => [
                        'room_id' => $roomId,
                        'settlement_data' => [],
                        'total_transactions' => $totalTransactions,
                        'generated_at' => date('Y-m-d H:i:s')
                    ]
                ];
            }

            // 检查是否有有意义的交易数据
            $hasSignificantTransactions = false;
            foreach ($settlementData as $userSettlement) {
                if ($userSettlement['total_score'] != 0 || count($userSettlement['payments']) > 1) {
                    $hasSignificantTransactions = true;
                    break;
                }
            }

            if (!$hasSignificantTransactions) {
                // 即使没有有意义的交易数据，也允许房主结算房间
                return [
                    'success' => true,
                    'data' => [
                        'room_id' => $roomId,
                        'settlement_data' => $settlementData,
                        'total_transactions' => $totalTransactions,
                        'generated_at' => date('Y-m-d H:i:s')
                    ]
                ];
            }

            return [
                'success' => true,
                'data' => [
                    'room_id' => $roomId,
                    'settlement_data' => $settlementData,
                    'total_transactions' => $totalTransactions,
                    'generated_at' => date('Y-m-d H:i:s')
                ]
            ];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => '获取房间结算失败：' . $e->getMessage()];
        }
    }

    /**
     * 记录交易审计日志
     */
    private function logTransaction($record, $roomId, $fromUserId, $toUserId, $score)
    {
        try {
            $fromUser = \app\model\User::find($fromUserId);
            $toUser = \app\model\User::find($toUserId);
            $room = \app\model\Room::find($roomId);
            
            $auditLog = [
                'transaction_id' => $record->id,
                'room_id' => $roomId,
                'room_code' => $room ? $room->room_code : 'unknown',
                'from_user_id' => $fromUserId,
                'from_user_nickname' => $fromUser ? $fromUser->nickname : 'unknown',
                'to_user_id' => $toUserId,
                'to_user_nickname' => $toUser ? $toUser->nickname : 'unknown',
                'score' => $score,
                'type' => $record->type,
                'description' => $record->description,
                'timestamp' => date('Y-m-d H:i:s'),
                'ip_address' => request()->getRealIp(),
                'user_agent' => request()->header('User-Agent', 'unknown')
            ];
            
            // 记录到日志文件
            error_log('交易审计日志: ' . json_encode($auditLog, JSON_UNESCAPED_UNICODE));
            
            // 可以在这里添加数据库审计表记录
            // $this->saveAuditLog($auditLog);
            
        } catch (\Exception $e) {
            error_log('记录交易审计日志失败: ' . $e->getMessage());
            // 审计日志失败不影响主要功能
        }
    }

    /**
     * 获取交易流水记录
     */
    public function getTransactionHistory(Request $request): Response
    {
        $roomId = $request->get('room_id');
        $userId = $request->get('user_id');
        // 安全获取分页参数，确保是有效的整数
        $page = (int)$request->get('page', 1);
        $limit = (int)$request->get('limit', 20);

        // 验证分页参数的有效性
        if ($page < 1) {
            $page = 1;
        }
        if ($limit < 1 || $limit > 100) {
            $limit = 20; // 默认值，最大100
        }

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            $query = \app\model\AccountingRecord::where('room_id', $roomId)
                ->with(['user', 'targetUser'])
                ->orderBy('created_at', 'desc');

            // 如果指定了用户ID，只查询该用户相关的记录
            if ($userId) {
                $query->where(function($q) use ($userId) {
                    $q->where('user_id', $userId)
                      ->orWhere('target_user_id', $userId);
                });
            }

            // 分页查询
            $records = $query->paginate($limit, ['*'], 'page', $page);

            // 格式化记录数据
            $formattedRecords = $records->map(function($record) {
                return [
                    'id' => $record->id,
                    'transaction_id' => $record->id,
                    'from_user' => [
                        'id' => $record->user->id,
                        'nickname' => $record->user->nickname,
                        'avatar' => $record->user->avatar
                    ],
                    'to_user' => [
                        'id' => $record->targetUser->id,
                        'nickname' => $record->targetUser->nickname,
                        'avatar' => $record->targetUser->avatar
                    ],
                    'score' => $record->score,
                    'type' => $record->type,
                    'description' => $record->description,
                    'is_settled' => $record->is_settled,
                    'created_at' => $record->created_at->format('Y-m-d H:i:s'),
                    'updated_at' => $record->updated_at->format('Y-m-d H:i:s')
                ];
            });

            return json([
                'success' => true,
                'data' => [
                    'records' => $formattedRecords,
                    'pagination' => [
                        'current_page' => $records->currentPage(),
                        'per_page' => $records->perPage(),
                        'total' => $records->total(),
                        'last_page' => $records->lastPage(),
                        'has_more' => $records->hasMorePages()
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取交易流水失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取交易流水失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取用户分数变化历史
     */
    public function getUserScoreHistory(Request $request): Response
    {
        $roomId = $request->get('room_id');
        $userId = $request->get('user_id');

        if (!$roomId || !$userId) {
            return json(['success' => false, 'message' => '房间ID和用户ID不能为空']);
        }

        try {
            // 获取用户在该房间的所有相关记录，只获取score类型的记录
            $records = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)
                          ->orWhere('target_user_id', $userId);
                })
                ->where('type', 'score') // 只获取score类型的记录
                ->with(['user', 'targetUser'])
                ->orderBy('created_at', 'asc')
                ->get();

            // 计算分数变化历史
            $scoreHistory = [];
            $currentScore = 0;

            foreach ($records as $record) {
                if ($record->target_user_id == $userId) {
                    // 别人给当前用户记分
                    $currentScore += $record->score;
                    $scoreHistory[] = [
                        'transaction_id' => $record->id,
                        'type' => 'received',
                        'from_user' => $record->user->nickname,
                        'score_change' => $record->score,
                        'score_after' => $currentScore,
                        'description' => $record->description,
                        'created_at' => $record->created_at->format('Y-m-d H:i:s')
                    ];
                } else {
                    // 当前用户给别人记分
                    $scoreHistory[] = [
                        'transaction_id' => $record->id,
                        'type' => 'given',
                        'to_user' => $record->targetUser->nickname,
                        'score_change' => $record->score,
                        'score_after' => $currentScore, // 给别人记分不影响自己的分数
                        'description' => $record->description,
                        'created_at' => $record->created_at->format('Y-m-d H:i:s')
                    ];
                }
            }

            return json([
                'success' => true,
                'data' => [
                    'user_id' => $userId,
                    'room_id' => $roomId,
                    'final_score' => $currentScore,
                    'score_history' => $scoreHistory,
                    'total_transactions' => count($records)
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户分数历史失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取用户分数历史失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新用户总分数
     */
    private function updateUsersTotalScore($settlementData)
    {
        try {
            foreach ($settlementData as $userSettlement) {
                $userId = $userSettlement['user_id'];
                $totalScore = $userSettlement['total_score'];
                
                if ($totalScore != 0) {
                    $user = \app\model\User::find($userId);
                    if ($user) {
                        $user->updateTotalScore($totalScore);
                        error_log("用户总分数已更新: user_id={$userId}, score_change={$totalScore}, new_total_score={$user->total_score}");
                    }
                }
            }
        } catch (\Exception $e) {
            error_log('更新用户总分数失败: ' . $e->getMessage());
            // 不影响主要功能
        }
    }

    /**
     * 标记房间为已结算
     */
    private function markRoomAsSettled($roomId)
    {
        try {
            $room = \app\model\Room::find($roomId);
            if ($room) {
                $room->status = 'finished';
                $room->save();
                error_log("房间已标记为结算: room_id={$roomId}");
            }
        } catch (\Exception $e) {
            error_log('标记房间结算失败: ' . $e->getMessage());
            throw $e; // 重新抛出异常，让事务回滚
        }
    }

    /**
     * 标记所有相关记录为已结算
     */
    private function markRecordsAsSettled($roomId)
    {
        try {
            $updatedCount = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where('is_settled', 0)
                ->update(['is_settled' => 1]);
            
            error_log("标记记录为已结算: room_id={$roomId}, updated_count={$updatedCount}");
            return $updatedCount;
        } catch (\Exception $e) {
            error_log('标记记录结算失败: ' . $e->getMessage());
            throw $e; // 重新抛出异常，让事务回滚
        }
    }

    /**
     * 手动触发自动结算
     */
    public function triggerAutoSettlement(Request $request): Response
    {
        try {
            $autoSettlementService = \app\service\AutoSettlementService::getInstance();
            $result = $autoSettlementService->processAutoSettlement();
            
            return json([
                'success' => true,
                'message' => '自动结算执行完成',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            error_log('手动触发自动结算失败: ' . $e->getMessage());
            return json([
                'success' => false,
                'message' => '自动结算执行失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 手动结算房间并发送通知
     */
    public function getRoomSettlementAndNotify(Request $request): Response
    {
        $roomId = $request->post('room_id');
        $userId = $request->post('user_id'); // 发起结算的用户ID

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            // 权限校验：检查用户是否为房主或超级管理员
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }

            // 检查房间状态
            if ($room->status === 'finished') {
                return json(['success' => false, 'message' => '房间已经结算，无法重复结算']);
            }

            // 检查是否为房主（使用严格比较，确保类型一致）
            $isOwner = (int)$room->created_by === (int)$userId;
            
            // 检查是否为超级管理员
            $isSuperAdmin = $this->isSuperAdmin($userId);

            if (!$isOwner && !$isSuperAdmin) {
                return json(['success' => false, 'message' => '权限不足，只有房主才能手动结算']);
            }

            // 检查房间内活跃用户数量（至少需要2个人才能结算）
            $activeUsersCount = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->count();

            if ($activeUsersCount < 2) {
                return json([
                    'success' => false, 
                    'message' => "房间内只有{$activeUsersCount}人，至少需要2人才能结算"
                ]);
            }

            // 获取结算数据
            $settlementResult = $this->getRoomSettlementData($roomId);
            
            if (!$settlementResult['success']) {
                return json($settlementResult);
            }
            
            // 检查是否有用户和交易记录
            $hasUsers = !empty($settlementResult['data']['settlement_data']);
            $hasTransactions = $settlementResult['data']['total_transactions'] > 0;
            
            // 根据情况确定返回状态
            $settlementStatus = 'normal'; // 默认正常结算
            if (!$hasUsers) {
                $settlementStatus = 'no_users'; // 没有用户
            } elseif (!$hasTransactions) {
                $settlementStatus = 'no_transactions'; // 没有交易记录
            }

            // 记录手动结算活动
            try {
                // 获取房主信息
                $room = \app\model\Room::find($roomId);
                $ownerId = $room ? $room->created_by : null;
                
                \app\model\AccountingRecord::create([
                    'room_id' => $roomId,
                    'user_id' => $ownerId, // 房主发起的操作
                    'target_user_id' => null,
                    'score' => 0,
                    'type' => 'manual_settlement',
                    'description' => '房主手动触发房间结算',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            } catch (\Exception $recordException) {
                error_log('记录手动结算活动失败: ' . $recordException->getMessage());
                // 记录失败不影响主要功能
            }

            // 更新房间状态为已结算并强制所有用户离开房间（在发送WebSocket消息之前完成）
            try {
                $room = \app\model\Room::find($roomId);
                if ($room) {
                    // 强制所有房间用户状态更新为已结算（包括活跃和已离开的用户）
                    \app\model\RoomUser::where('room_id', $roomId)
                        ->whereIn('status', [\app\model\RoomUser::STATUS_ACTIVE, \app\model\RoomUser::STATUS_LEFT])
                        ->update([
                            'status' => \app\model\RoomUser::STATUS_FINISHED,
                            'left_at' => date('Y-m-d H:i:s')
                        ]);
                    
                    // 更新房间状态为已结算
                    $room->status = 'finished';
                    $room->current_players = 0; // 结算后房间人数为0
                    $saveResult = $room->save();
                    
                    // 更新所有记账记录为已结算
                    \app\model\AccountingRecord::where('room_id', $roomId)
                        ->update(['is_settled' => 1]);
                    
                    // 创建房间结算汇总记录
                    try {
                        $settlementReason = '手动结算';
                        if ($settlementStatus === 'no_users') {
                            $settlementReason = '手动结算（无用户）';
                        } elseif ($settlementStatus === 'no_transactions') {
                            $settlementReason = '手动结算（无交易记录）';
                        }
                        
                        \app\model\RoomSettlement::createSettlement($roomId, 'manual', $settlementReason);
                        error_log("房间结算汇总记录创建成功: room_id={$roomId}");
                    } catch (\Exception $settlementException) {
                        error_log('创建房间结算汇总记录失败: ' . $settlementException->getMessage());
                        // 汇总记录创建失败不影响主要功能
                    }
                    
                    error_log("房间结算完成: room_id={$roomId}, 保存结果: " . ($saveResult ? '成功' : '失败'));
                    error_log("房间状态更新: status={$room->status}");
                    
                    // 刷新房间模型以获取最新状态
                    $room->refresh();
                }
            } catch (\Exception $roomException) {
                error_log('更新房间状态失败: ' . $roomException->getMessage());
                // 房间状态更新失败不影响主要功能
            }

            // 发送WebSocket通知给房间内所有用户（在房间状态更新后发送，确保消息中包含最新状态）
            try {
                $websocketService = \app\service\WebSocketService::getInstance();
                $websocketService->sendRoomSettlementMessage($roomId, $settlementResult['data']);
                
                // 发送房间状态变化消息，通知所有用户房间已结算
                $room = \app\model\Room::find($roomId);
                if ($room) {
                    $websocketService->sendRoomStatusChangedMessage($roomId, [
                        'status' => 'finished',
                        'message' => '房间已结算，所有玩家已离开',
                        'current_players' => 0
                    ]);
                }
            } catch (\Exception $wsException) {
                error_log('发送结算WebSocket消息失败: ' . $wsException->getMessage());
                // WebSocket消息发送失败不影响主要功能
            }

            return json([
                'success' => true,
                'message' => '房间结算成功',
                'data' => $settlementResult['data'],
                'settlement_status' => $settlementStatus // 添加结算状态
            ]);

        } catch (\Exception $e) {
            error_log('手动结算失败: ' . $e->getMessage());
            return json([
                'success' => false,
                'message' => '结算失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 检查用户是否为超级管理员
     */
    private function isSuperAdmin($userId)
    {
        // 这里可以根据实际需求定义超级管理员的判断逻辑
        // 例如：检查用户表中的is_admin字段，或者检查特定的用户ID列表
        
        // 方法1：检查用户表中的is_admin字段（如果存在）
        try {
            $user = \app\model\User::find($userId);
            if ($user && isset($user->is_admin) && $user->is_admin == 1) {
                return true;
            }
        } catch (\Exception $e) {
            // 如果用户表没有is_admin字段，忽略错误
        }
        
        // 方法2：检查预定义的超级管理员ID列表
        $superAdminIds = [
            // 在这里添加超级管理员的用户ID
            // 例如：1, 2, 3
        ];
        
        if (in_array($userId, $superAdminIds)) {
            return true;
        }
        
        // 方法3：检查环境变量中的超级管理员配置
        $envSuperAdmins = env('SUPER_ADMIN_IDS', '');
        if ($envSuperAdmins) {
            $adminIds = explode(',', $envSuperAdmins);
            $adminIds = array_map('trim', $adminIds);
            if (in_array($userId, $adminIds)) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * 获取用户历史房间数据
     */
    public function getUserRoomHistory(Request $request): Response
    {
        $userId = $request->get('user_id');

        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            // 获取用户参与过的所有房间
            $roomUsers = \app\model\RoomUser::where('user_id', $userId)
                ->with(['room', 'user'])
                ->orderBy('joined_at', 'desc')
                ->get();

            $rooms = [];
            $winCount = 0;
            $lossCount = 0;
            $totalScore = 0;

            foreach ($roomUsers as $roomUser) {
                $room = $roomUser->room;
                if (!$room || $room->status !== 'finished') {
                    continue; // 只统计已结算的房间
                }

                $finalScore = $roomUser->current_score;
                $totalScore += $finalScore;

                if ($finalScore >= 0) {
                    $winCount++;
                } else {
                    $lossCount++;
                }

                // 获取对手信息（房间内其他用户）
                $opponents = \app\model\RoomUser::where('room_id', $room->id)
                    ->where('user_id', '!=', $userId)
                    ->with('user')
                    ->get();

                $opponentInfo = null;
                if ($opponents->isNotEmpty()) {
                    $opponent = $opponents->first();
                    $opponentInfo = [
                        'name' => $opponent->user->nickname ?? '未知',
                        'score' => $opponent->current_score ?? 0
                    ];
                }

                // 获取茶饭分数（如果有的话）
                $teaScore = 0;
                $teaRecords = \app\model\AccountingRecord::where('room_id', $room->id)
                    ->where('type', 'tea_meal')
                    ->where('user_id', $userId)
                    ->sum('score');
                if ($teaRecords) {
                    $teaScore = $teaRecords;
                }

                $rooms[] = [
                    'id' => $room->id,
                    'room_code' => $room->room_code,
                    'final_score' => $finalScore,
                    'result' => $finalScore >= 0 ? 'win' : 'loss',
                    'opponent_name' => $opponentInfo['name'] ?? '未知',
                    'opponent_score' => $opponentInfo['score'] ?? 0,
                    'tea_score' => $teaScore,
                    'created_at' => $room->settled_at ?? $room->created_at,
                    'settled_at' => $room->settled_at
                ];
            }

            // 计算胜率
            $totalGames = $winCount + $lossCount;
            $winRate = $totalGames > 0 ? round(($winCount / $totalGames) * 100, 1) : 0;

            return json([
                'success' => true,
                'data' => [
                    'rooms' => $rooms,
                    'winCount' => $winCount,
                    'lossCount' => $lossCount,
                    'totalScore' => $totalScore,
                    'winRate' => $winRate
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户历史房间失败: ' . $e->getMessage());
            return json([
                'success' => false,
                'message' => '获取历史房间失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 个人结算并离开房间（只结算自己）
     */
    public function personalSettlement(Request $request): Response
    {
        $roomId = $request->post('room_id');
        $userId = $request->post('user_id');

        if (!$roomId || !$userId) {
            return json(['success' => false, 'message' => '参数不完整']);
        }

        try {
            // 检查房间是否存在
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }

            // 检查房间状态
            if ($room->status === 'finished') {
                return json(['success' => false, 'message' => '房间已结算，无法进行个人结算']);
            }

            // 检查用户是否在房间中
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->first();

            if (!$roomUser) {
                return json(['success' => false, 'message' => '用户不在房间中或已离开']);
            }

            // 获取用户在该房间的所有记录
            $userRecords = \app\model\AccountingRecord::where('room_id', $roomId)
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)
                          ->orWhere('target_user_id', $userId);
                })
                ->where('is_settled', 0) // 只计算未结算的记录
                ->get();

            if ($userRecords->isEmpty()) {
                return json(['success' => false, 'message' => '没有需要结算的记录']);
            }

            // 计算所有用户在房间的最终分数
            $allRoomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->get();

            $userScores = [];
            foreach ($allRoomUsers as $roomUser) {
                $userRecords = \app\model\AccountingRecord::where('room_id', $roomId)
                    ->where(function($query) use ($roomUser) {
                        $query->where('user_id', $roomUser->user_id)
                              ->orWhere('target_user_id', $roomUser->user_id);
                    })
                    ->where('is_settled', 0)
                    ->get();

                $userScore = 0;
                foreach ($userRecords as $record) {
                    if ($record->user_id == $roomUser->user_id) {
                        $userScore += $record->score;
                    } elseif ($record->target_user_id == $roomUser->user_id) {
                        $userScore -= $record->score;
                    }
                }
                $userScores[$roomUser->user_id] = $userScore;
            }

            $finalScore = $userScores[$userId] ?? 0;

            // 智能结算逻辑：如果离开的用户是赢家，则全员结算
            $shouldSettleAll = $finalScore > 0; // 赢家离开需要全员结算

            if ($shouldSettleAll) {
                // 全员结算：为所有用户生成结算记录
                $settledUsers = [];
                foreach ($allRoomUsers as $roomUser) {
                    $userScore = $userScores[$roomUser->user_id] ?? 0;
                    $user = \app\model\User::find($roomUser->user_id);
                    
                    if ($user) {
                        // 更新用户的total_score
                        $user->increment('total_score', $userScore);
                        
                        // 标记该用户的所有记录为已结算
                        \app\model\AccountingRecord::where('room_id', $roomId)
                            ->where(function($query) use ($roomUser) {
                                $query->where('user_id', $roomUser->user_id)
                                      ->orWhere('target_user_id', $roomUser->user_id);
                            })
                            ->update(['is_settled' => 1]);
                        
                        // 更新用户状态为已结算并离开
                        $roomUser->status = \app\model\RoomUser::STATUS_FINISHED;
                        $roomUser->current_score = $userScore;
                        $roomUser->left_at = date('Y-m-d H:i:s');
                        $roomUser->save();
                        
                        // 创建个人结算记录
                        \app\model\RoomSettlementDetail::create([
                            'settlement_id' => null,
                            'room_id' => $roomId,
                            'user_id' => $roomUser->user_id,
                            'username' => $user->nickname ?? '未知用户',
                            'final_score' => $userScore,
                            'is_winner' => $userScore > 0,
                            'is_room_owner' => $room->created_by == $roomUser->user_id,
                            'joined_at' => $roomUser->joined_at,
                            'left_at' => $roomUser->left_at,
                            'settlement_strategy' => null
                        ]);
                        
                        $settledUsers[] = [
                            'user_id' => $roomUser->user_id,
                            'username' => $user->nickname ?? '未知用户',
                            'final_score' => $userScore,
                            'is_winner' => $userScore > 0
                        ];
                    }
                }

                // 更新房间状态为已结算
                $room->status = 'finished';
                $room->current_players = 0;
                $room->save();

                $message = '赢家离开，房间已全员结算';
            } else {
                // 个人结算：只结算当前用户
                $user = \app\model\User::find($userId);
                if ($user) {
                    $user->increment('total_score', $finalScore);
                }

                // 标记该用户的所有记录为已结算
                \app\model\AccountingRecord::where('room_id', $roomId)
                    ->where(function($query) use ($userId) {
                        $query->where('user_id', $userId)
                              ->orWhere('target_user_id', $userId);
                    })
                    ->update(['is_settled' => 1]);

                // 更新用户状态为已结算并离开
                $roomUser->status = \app\model\RoomUser::STATUS_FINISHED;
                $roomUser->current_score = $finalScore;
                $roomUser->left_at = date('Y-m-d H:i:s');
                $roomUser->save();

                // 创建个人结算记录
                \app\model\RoomSettlementDetail::create([
                    'settlement_id' => null,
                    'room_id' => $roomId,
                    'user_id' => $userId,
                    'username' => $user->nickname ?? '未知用户',
                    'final_score' => $finalScore,
                    'is_winner' => $finalScore > 0,
                    'is_room_owner' => $room->created_by == $userId,
                    'joined_at' => $roomUser->joined_at,
                    'left_at' => $roomUser->left_at,
                    'settlement_strategy' => null
                ]);

                // 更新房间当前人数
                $room->updateCurrentPlayers();

                $message = '个人结算成功，其他玩家可以继续游戏';
            }

            // 发送WebSocket通知
            try {
                $websocketService = \app\service\WebSocketService::getInstance();
                $websocketService->sendPersonalSettlementMessage($roomId, $userId, [
                    'user_id' => $userId,
                    'username' => $user->nickname ?? '未知用户',
                    'final_score' => $finalScore,
                    'is_winner' => $finalScore > 0,
                    'settlement_time' => date('Y-m-d H:i:s')
                ]);
            } catch (\Exception $wsException) {
                error_log('发送个人结算WebSocket消息失败: ' . $wsException->getMessage());
            }

            return json([
                'success' => true,
                'data' => [
                    'message' => $message,
                    'final_score' => $finalScore,
                    'is_winner' => $finalScore > 0,
                    'user_id' => $userId,
                    'room_id' => $roomId,
                    'settled_all' => $shouldSettleAll
                ]
            ]);

        } catch (\Exception $e) {
            error_log('个人结算失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '个人结算失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取房间结算建议
     */
    public function getSettlementSuggestion(Request $request): Response
    {
        $roomId = $request->get('room_id');

        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            // 获取房间内所有活跃用户
            $allRoomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->get();

            if ($allRoomUsers->isEmpty()) {
                return json(['success' => false, 'message' => '房间内没有活跃用户']);
            }

            // 计算所有用户的分数
            $userScores = [];
            $totalScore = 0;
            $hasPositive = false;
            $hasNegative = false;

            foreach ($allRoomUsers as $roomUser) {
                $userRecords = \app\model\AccountingRecord::where('room_id', $roomId)
                    ->where(function($query) use ($roomUser) {
                        $query->where('user_id', $roomUser->user_id)
                              ->orWhere('target_user_id', $roomUser->user_id);
                    })
                    ->where('is_settled', 0)
                    ->get();

                $userScore = 0;
                foreach ($userRecords as $record) {
                    if ($record->user_id == $roomUser->user_id) {
                        $userScore += $record->score;
                    } elseif ($record->target_user_id == $roomUser->user_id) {
                        $userScore -= $record->score;
                    }
                }
                
                $userScores[$roomUser->user_id] = $userScore;
                $totalScore += $userScore;
                
                if ($userScore > 0) $hasPositive = true;
                if ($userScore < 0) $hasNegative = true;
            }

            // 分析结算建议
            $suggestion = [
                'should_settle_all' => false,
                'reason' => '',
                'user_scores' => $userScores,
                'total_score' => $totalScore
            ];

            // 如果总分为0且有人正分有人负分，建议全员结算
            if (abs($totalScore) < 0.01 && $hasPositive && $hasNegative) {
                $suggestion['should_settle_all'] = true;
                $suggestion['reason'] = '当前房间积分平衡，建议全员结算';
            }
            // 如果只有一个人有积分变化，建议个人结算
            elseif (count(array_filter($userScores, function($score) { return abs($score) > 0.01; })) == 1) {
                $suggestion['should_settle_all'] = false;
                $suggestion['reason'] = '只有一人有积分变化，建议个人结算';
            }
            // 其他情况建议个人结算
            else {
                $suggestion['should_settle_all'] = false;
                $suggestion['reason'] = '建议个人结算，其他玩家可继续游戏';
            }

            return json([
                'success' => true,
                'data' => $suggestion
            ]);

        } catch (\Exception $e) {
            error_log('获取结算建议失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取结算建议失败：' . $e->getMessage()]);
        }
    }
}
